import React, { useMemo, useState } from "react";
import { Button, DatePicker, Form, Input, Space, Table, Image, Modal } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from 'antd/es/table';
import { accountFundTypes } from "@/constants/types";
import { calculateTableWidth } from "@/utils/util";
import { useComponentDidMount } from "@/hooks";
import AccountFundAdd from "../modals/AccountFundAdd";
import { useRequest } from "ahooks";
import { accountFlowList, accountFlowTabNum, accountFlowAdd, accountFlowConfirm } from "../services";
import XlRadio from "@/components/Form/XlRadio";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";

const {Item} = Form;

const AccountFunds = () => {
  const [form] = Form.useForm();

  //
  const [visible, setVisible] = useState(false);
  const { loading: addLoading, runAsync: addApi} = useRequest(accountFlowAdd, {manual: true});

  const statusMaps: any [] = [
    {
      label: "全部",
      value: "all",
      num: "totalNum"

    },
    {
      label: "入账",
      value: "1",
      num: "incomeNum"
    },
    {
      label: "出账",
      value: "2",
      num: "outcomeNum"
    }
  ];

  // order status 
  const [status, setStatus] = useState<string>('all');
  const [tabNumObj, setTabNumObj] = useState<any>({});


  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    total: 0,
    pageNum: 1,
    pageSize: 20
  });


  const getParams = () => {
    const params = form.getFieldsValue();
    return {
      ...params,
      startTime: params?.time?.[0] ? params?.time?.[0].format("YYYY-MM-DD 00:00:00") : undefined,
      endTime: params?.time?.[1] ? params?.time?.[1].format("YYYY-MM-DD 23:59:59") : undefined,
      time: undefined
    }
  }

  const fetchTabNumApi = async (params: any = {}) => {
    const res = await accountFlowTabNum({
      ...params,
    });
    setTabNumObj(res || {});
  }
  
  const search = async (params: any) => {
    const res = await accountFlowList({
      ...params,
      type: params?.type === "all" ? undefined : params.type
    });
    setDataSource(res?.data || []);
    setPagination({
      total: res?.total,
      pageNum: res?.pageNum,
      pageSize: res?.pageSize
    });
  }

  const refreshData = () => {
    const params = getParams();
    search({
      ...params,
      type: status,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi(params);
  }

  const addProps = {
    title: "新增账户资金记录",
    loading: addLoading,
    visible,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await addApi(params);
      if (res?.code === "0") {
        addProps.onCancel();
        refreshData();
      }
      
    }
  }
  
  // 新建
  const handleAdd = () => {
    setVisible(true);
  }
  // status change
  const handleStatusChange = (val: any) => {
    const params = getParams();
    setStatus(val?.value);
    search({
      ...params,
      type: val?.value,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi();
  }

  const handleConfirm = (record: accountFundTypes) => {
    Modal.confirm({
      title: "温馨提示",
      content: `资金出入 ${record?.amount}, 是否确认此流水？`,
      onOk:async () => {
        accountFlowConfirm({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              refreshData();
            }
          }
        )
      }
    });
  }

  const columns: ColumnsType<accountFundTypes> = [
    {
      title: "客户编码",
      dataIndex: "customerCode",
    },
    {
      title: "公司简称",
      dataIndex: "customerName",
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (_, record) => <span>{+record?.status === 1 ? '已确认' : '待确认'}</span>
    },
    {
      title: "资金出入",
      dataIndex: "amount",
    },  
    {
      title: "业务类型",
      dataIndex: "category",
      render: (_, record) => <XlTableDictColumn value={record?.category} type="accChangeType" />
    },
    {
      title: "备注",
      dataIndex: "remark",
      ellipsis: true,
    },
    {
      title: "账户余额",
      dataIndex: "balance",
    },
    {
      title: "业务时间",
      dataIndex: "businessTime",
    },
    {
      title: '水单',
      dataIndex: 'memoPath',
      render: (_, record: any) => {
        if (!record?.memoPath) {
          return "";
        }
        return (
          <Image src={record?.memoPath} width={100} height={100} />
        )
      }
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      dataIndex: 'options',
      render: (_, record: any) => {
        return (
          <Space>
            {+record?.status !== 1 && <Button type="link" onClick={() => handleConfirm(record)}>确认</Button>}
          </Space>
        );
      }
    },
  ];

  const composeOrderStatusMaps = useMemo(() => {
    return statusMaps.map(v => ({
      ...v,
      label: tabNumObj?.[v?.num] > 0 ? `${v?.label} (${tabNumObj?.[v?.num]})` : v.label
    }))
  }, [JSON.stringify(tabNumObj), JSON.stringify(statusMaps)]);

  const handleSearch = () => {
    const params = getParams();
    search({
      ...params,
      type: status,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi(params);
  }
  const handleReset = () => {
    form.resetFields();
    search({
      type: status,
      pageNum: 1,
      pageSize: 20
    });
  }

  useComponentDidMount(() => {
    search({
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi();
  })

  return (
    <>
      <Form form={form} layout="inline">
        <Item label="时间" name="time" style={{marginBottom: 15}}>
          <DatePicker.RangePicker />
        </Item>
        <Item label="公司简称" name="customerName" style={{marginBottom: 15}}>
          <Input onPressEnter={handleSearch} />
        </Item>
        
        <Space style={{marginBottom: 20}}>
          <Button type="primary" onClick={handleSearch}>查询</Button>
          <Button type="default" onClick={handleReset}>重置</Button>
        </Space>
      </Form>
      <div style={{display: 'flex', justifyContent:'space-between', flexWrap: 'wrap'}}>
        <div >
          <XlRadio.ButtonRadioGroup value={status} onChange={(val: string []) => handleStatusChange(val)} options={composeOrderStatusMaps} />
        </div>
        <Space style={{display: 'flex', justifyContent: 'flex-end', }}>
          <Button type="primary" onClick={handleAdd}><PlusOutlined />账户资金记录</Button>
        </Space>
      </div>
      <Table
        className="mt10"
        rowKey="id"
        bordered
        dataSource={dataSource}
        columns={columns}
        scroll={{x: calculateTableWidth(columns), y: 580}}
        pagination={{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            const params = getParams();
            search({
              ...params,
              pageNum,
              pageSize
            });
          }
        }}
      />
      {visible && <AccountFundAdd {...addProps} />}
    </>
  );
}
export default AccountFunds;